<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Model\ConfigModel;
use Illuminate\Http\Request;

class ConfigController extends Controller
{
    protected $form_name = [
        'config_type','config_title','config_keywords','config_description'
    ];
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('admin.config.index');
    }

    public function list(Request $request)
    {
        $page = $request->page ? : 1;
        $limit = $request ->limit ? : 10;

        $data['code'] = 0;
        $data['msg'] = '成功';
        $data['count'] = ConfigModel::count();
        $data['data'] = ConfigModel::skip($limit * ($page -1))
            ->take($limit)
            ->get();
        return $data;
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.config.add');
    }

    /**
     * @param Request $request
     * @return array
     */
    public function store(Request $request)
    {
        $data = $request->only($this->form_name);
        $Config = new ConfigModel();
        foreach ($this->form_name as $v){
            $Config ->$v = $data[ $v ];
        }
        if ($Config->save()){
            return $this->res_msg(0,'成功');
        }else{
            return  $this->res_msg(1,'失败');
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $config = ConfigModel::findOrFail($id);

        $data['id'] = $id;
        $data['info'] = $config;
        return view('admin.config.edit')->with('data',$data);
    }

    /**
     * @param Request $request
     * @param $id
     * @return array
     */
    public function update(Request $request, $id)
    {
        $config = ConfigModel::findOrFail($id);

        foreach ($this->form_name as $v){
            $config -> $v = $request->get($v);
        }
        if ($config->save()){
            return $this->res_msg(0,'成功');
        }else{
            return  $this->res_msg(1,'失败');
        }
    }

    /**
     * @param $id
     * @return array
     */
    public function destroy($id)
    {
        $config = ConfigModel::findOrFail($id);
        if ($config->delete()){
            return $this->res_msg(0,'成功');
        }else{
            return $this->res_msg(1,'失败');
        }
    }


}
